import { useState } from 'react';
import { message, Layout, Result } from 'antd';
import * as XLSX from 'xlsx';
import './Excel2JSON.css';

const staticMessageText = {
  noData: '暂无数据',
  importSucceed: '上传成功！',
  importFailed: '上传失败！',
  fileTypeError: '文件类型错误！',
  copySucceed: '复制成功！',
  copyFailed: '复制失败！',
};
const allowedTypes = ['xlsx', 'xls'];
const { Content } = Layout;

const Excel2JSON = (props: any) => {
  const { setIsLoading } = props;
  // 用于文件内容回显
  const [currentResultList, setCurrentResultList]: any[] = useState([]);
  // 用于文件名回显
  const [currentFileName, setCurrentFileName]: any[] = useState('');

  // 点击上传
  const handleImportClick = () => {
    document.getElementById('importExcel')?.click();
  };

  // 上传Excel以及转化
  const handleImportExcel = (file: any) => {
    setIsLoading(true);
    // 1.获取到上传的文件对象
    const { files } = file.target;
    const { name = '' } = files[0];
    // 判断文件类型
    const fileType = name.substring(name.lastIndexOf('.') + 1);
    if (!name || !allowedTypes.includes(fileType)) {
      message.error(staticMessageText.fileTypeError);
      setIsLoading(false);
      return;
    }
    setCurrentFileName(name);

    // 2.通过FileReader对象读取文件对象
    const fileReader = new FileReader();
    // 4.保存获取到的数据
    let currentFileData: any[] = [];
    fileReader.onload = (event) => {
      try {
        // 4.1 以二进制读取到整份Excel
        const workBook = XLSX.read(event.target?.result, { type: 'binary' });
        // 4.2 遍历每张工作表
        // eslint-disable-next-line no-restricted-syntax
        for (const sheet in workBook.Sheets) {
          if (Object.prototype.hasOwnProperty.call(workBook.Sheets, sheet)) {
            // 4.3 使用 sheet_to_json 转化成 json 数据
            const element = workBook.Sheets[sheet];
            currentFileData = currentFileData.concat(
              XLSX.utils.sheet_to_json(element)
            );
          } else {
            message.error(staticMessageText.fileTypeError);
            break;
          }
        }
        setCurrentResultList(currentFileData);
        message.success(staticMessageText.importSucceed);
        setIsLoading(false);
      } catch (error) {
        message.error(staticMessageText.fileTypeError);
      }
    };
    // 3.以二进制方式打开
    fileReader.readAsBinaryString(files[0]);
  };
  // 复制到剪切板
  const handleCopyClick = () => {
    const clipboardObj = navigator.clipboard;
    const resultJSON = document.getElementById('contextJSON')?.innerText || '';
    try {
      setIsLoading(true);
      if (clipboardObj) {
        // eslint-disable-next-line promise/catch-or-return
        clipboardObj.writeText(resultJSON).then(
          // eslint-disable-next-line promise/always-return
          () => {
            message.success(staticMessageText.copySucceed);
            setIsLoading(false);
          },
          () => {
            message.error(staticMessageText.copyFailed);
          }
        );
      }
    } catch (error) {
      console.error(error);
    }
  };
  return (
    <div className="containerBox">
      <Layout className="layout">
        <Content
          style={{
            width: 'calc(100vw - 204px)',
            height: '100vh',
            padding: '50px',
            background:
              'linear-gradient( 200.96deg, #2afe58 -29.09%, #57cddd 51.77%, #3c6ffa 129.35% )',
          }}
        >
          {/* 上传按钮 */}
          <input
            id="importExcel"
            type="file"
            accept=".xlsx, .xls, xltx"
            onChange={handleImportExcel}
            style={{ display: 'none' }}
          />
          <button
            type="button"
            className="inputButton"
            onClick={handleImportClick}
          >
            <span role="img" aria-label="books">
              📚 点击上传
            </span>
          </button>
          {currentFileName ? (
            <span className="inputFileName" title={currentFileName}>
              {currentFileName}
            </span>
          ) : (
            ''
          )}
          {/* 文本显示 */}
          <div className="site-layout-content">
            <pre id="contextJSON">
              {Array.isArray(currentResultList) &&
              currentResultList.length > 0 ? (
                JSON.stringify(currentResultList, null, 2)
              ) : (
                <Result
                  status="404"
                  title=""
                  subTitle={staticMessageText.noData}
                />
              )}
            </pre>
          </div>
          {/* 复制按钮 */}
          <button
            type="button"
            className="copyButton"
            onClick={handleCopyClick}
            disabled={currentResultList.length <= 0}
          >
            <span role="img" aria-label="books">
              📋️ 复制到剪切板
            </span>
          </button>
        </Content>
      </Layout>
    </div>
  );
};
export default Excel2JSON;
